﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;


namespace EzDesk.Core.ServiceImpl.Common
{
    /// <summary>
    /// 解析Update模板的帮助类
    /// </summary>
    public static class UpdateTemplateHelper
    {
        /// <summary>
        /// 由模板转换成供给显示的内容
        /// </summary>
        /// <param name="template"></param>
        /// <param name="parameters"></param>
        /// <returns></returns>
        public static string ConvertToContentFromTemplate(string template, Dictionary<string, string> parameters)
        {
            if (String.IsNullOrEmpty(template))
            {
                return template;
            }
            Regex regex = new Regex(
                @"(?<={)\w+(?=})",
                RegexOptions.IgnoreCase | RegexOptions.Compiled
                );
                
            string stringInput = template;
            string result = template;
            MatchCollection coll = regex.Matches(stringInput);

            foreach(Match match in coll)
            {
                string variable = match.Value as string;
                if (parameters.Keys.Contains(variable))
                {
                    result = result.Replace("{" + variable + "}", parameters[variable]);
                }
                else
                {
                    //TODO: 包含没有定义的变量，抛出异常
                    throw new Exception();                    
                }
            }

            return result;
        }
    }
}
